import { useState, useEffect, useCallback } from 'react';
import { message } from 'antd';
import { teamApi } from '../../services';
import { Team, TeamMember, PageRequest } from '../../types/rbac';

// 团队表单数据类型
export interface TeamForm {
  name: string;
  code: string;
  description?: string;
  roles: string[];
  departmentId?: string;
  status: 'active' | 'inactive';
}

// 团队列表管理hook
export const useTeams = (params?: PageRequest & { keyword?: string; departmentId?: string | null }) => {
  const [teams, setTeams] = useState<Team[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);

  const fetchTeams = useCallback(async () => {
    try {
      setLoading(true);
      const result = await teamApi.getTeams({
        page: params?.page || 1,
        size: params?.size || 10,
        keyword: params?.keyword,
        departmentId: params?.departmentId
      });
      // 处理API响应，适配真实的响应体结构，并转换状态字段
      const processedTeams = (result.records || []).map((team: any) => ({
        ...team,
        status: team.status === 1 ? 'active' : 'inactive'
      }));
      setTeams(processedTeams);
      setTotal(result.totalElements || 0);
    } catch (error) {
      console.error('获取团队列表失败:', error);
      message.error('获取团队列表失败');
    } finally {
      setLoading(false);
    }
  }, [params?.page, params?.size, params?.keyword, params?.departmentId]);

  useEffect(() => {
    fetchTeams();
  }, [params?.page, params?.size, params?.keyword, params?.departmentId]);

  return {
    teams,
    loading,
    total,
    refresh: fetchTeams,
  };
};

// 团队详情管理hook
export const useTeam = (id?: string) => {
  const [team, setTeam] = useState<Team | null>(null);
  const [loading, setLoading] = useState(false);

  const fetchTeam = async (teamId: string) => {
    try {
      setLoading(true);
      const result = await teamApi.getTeam(teamId);
      setTeam(result);
    } catch (error) {
      console.error('获取团队详情失败:', error);
      message.error('获取团队详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (id) {
      fetchTeam(id);
    }
  }, [id]);

  return {
    team,
    loading,
    refresh: () => id && fetchTeam(id),
  };
};

// 团队操作管理hook
export const useTeamActions = () => {
  const [loading, setLoading] = useState(false);

  const createTeam = async (teamForm: TeamForm) => {
    try {
      setLoading(true);
      
      // 转换为Team格式，并将状态字符串转换为数字
      const team: Omit<Team, 'id' | 'createTime' | 'updateTime'> = {
        ...teamForm,
        // 将前端的字符串状态转换为后端期望的数字状态
        status: teamForm.status === 'active' ? 1 : 0,
        level: 1,
        memberCount: 0,
        createdBy: 'current-user', // TODO: 从用户上下文获取
      };
      
      const newTeam = await teamApi.createTeam(team);
      
      message.success('团队创建成功');
      return newTeam;
    } catch (error) {
      console.error('创建团队失败:', error);
      message.error('创建团队失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const updateTeam = async (id: string, data: Partial<Team>) => {
    try {
      setLoading(true);
      
      // 如果数据中包含状态字段，需要转换格式
      const processedData = { ...data, id }; // 将 id 添加到 data 中
      if (processedData.status && typeof processedData.status === 'string') {
        processedData.status = processedData.status === 'active' ? 1 : 0;
      }
      
      const updatedTeam = await teamApi.updateTeam(id, processedData);
      
      message.success('团队更新成功');
      return updatedTeam;
    } catch (error) {
      console.error('更新团队失败:', error);
      message.error('更新团队失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const deleteTeam = async (id: string) => {
    try {
      setLoading(true);
      await teamApi.deleteTeam(id);
      message.success('团队删除成功');
    } catch (error) {
      message.error('团队删除失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const deleteTeams = async (ids: string[]) => {
    try {
      setLoading(true);
      await teamApi.deleteTeams(ids);
      message.success(`成功删除 ${ids.length} 个团队`);
    } catch (error) {
      message.error('批量删除失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    createTeam,
    updateTeam,
    deleteTeam,
    deleteTeams,
  };
};

// 团队成员管理hook
export const useTeamMembers = (teamId?: string, params?: PageRequest) => {
  const [members, setMembers] = useState<TeamMember[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);

  const fetchMembers = async () => {
    if (!teamId) return;
    
    try {
      setLoading(true);
      // 调用真实API获取团队成员
      const response = await teamApi.getTeamMembers(teamId, params);
      setMembers(response.content || response.records || []);
      setTotal(response.totalElements || 0);
    } catch (error) {
      console.error('获取团队成员失败:', error);
      message.error('获取团队成员失败');
      setMembers([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMembers();
  }, [teamId, params?.page, params?.size]);

  const addMembers = async (userIds: string[]) => {
    if (!teamId) return;
    
    try {
      await teamApi.addTeamMembers(teamId, userIds);
      message.success('成员添加成功');
      fetchMembers();
    } catch (error) {
      message.error('成员添加失败');
      throw error;
    }
  };

  const removeMembers = async (userIds: string[]) => {
    if (!teamId) return;
    
    try {
      await teamApi.removeTeamMembers(teamId, userIds);
      message.success('成员移除成功');
      fetchMembers();
    } catch (error) {
      message.error('成员移除失败');
      throw error;
    }
  };

  return {
    members,
    loading,
    total,
    refresh: fetchMembers,
    addMembers,
    removeMembers,
  };
};